<template>
  <div>
    <div class="ele-body"
         style="padding-bottom: 71px">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="130px"
               @keyup.enter.native="submit"
               @submit.native.prevent>
        <el-card shadow="never"
                 header="商家信息"
                 body-style="padding: 22px 22px 0 22px;">
          <el-row :gutter="15">
            <el-col :lg="12"
                    :md="10">
              <el-form-item label="商家名称:"
                            label-width="130px"
                            prop="merchantName">
                <el-input v-model.trim="form.merchantName"
                          placeholder="请输入商家名称"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商家地址:"
                            label-width="130px"
                            prop="merchantAddress">
                <el-input v-model.trim="form.merchantAddress"
                          @focus="selPosition"
                          placeholder="请输入商家地址"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商家封面图:"
                            prop="browserIcon">
                <span slot="label">
                  商家封面图
                  <el-tooltip placement="top">
                    <div slot="content">
                      用于打开商家封面图展示<br />
                      大小尺寸为375px * 22px
                    </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>

                <div class="ele-image-upload-list">
                  <div class="ele-image-upload-item ele-image-upload-button"
                       @click="
                      modalPicTap('dan', 'merchantSurfaceDrawing', '商家封面图')
                    ">
                    <div>
                      <div tabindex="0"
                           class="el-upload el-upload--text">
                        <div class="el-upload-dragger">
                          <i class="el-icon-plus ele-image-upload-icon"></i>
                        </div>

                        <div class="ele-image-upload-item"
                             style="margin: 0 0 0 0"
                             v-if="form.merchantSurfaceDrawing">
                          <div class="el-image">
                            <img :src="form.merchantSurfaceDrawing"
                                 width="100%"
                                 height="100%"
                                 class="el-image__inner"
                                 style="object-fit: cover" />
                          </div>
                          <div class="ele-image-upload-close"
                               @click="handleRemove('merchantSurfaceDrawing')"><i class="el-icon-close"></i></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="商家详情图:"
                            prop="browserIcon">
                <span slot="label">
                  商家详情图
                  <el-tooltip placement="top">
                    <div slot="content"> 注:长高不限<br /> </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <EleImageUpload v-model="form.merchantDetailChart"
                                :limit="8"
                                :remove-handler="removeHandler"
                                @upload="onUpload" />
                <!-- <div class="ele-image-upload-list">
                  <div class="ele-image-upload-item ele-image-upload-button"
                       @click="
                      modalPicTap('dan', 'merchantDetailChart', '商家详情图')
                    ">
                    <div>
                      <div tabindex="0"
                           class="el-upload el-upload--text">
                        <div class="el-upload-dragger">
                          <i class="el-icon-plus ele-image-upload-icon"></i>
                        </div>

                        <div class="ele-image-upload-item"
                             style="margin: 0 0 0 0"
                             v-if="form.merchantDetailChart">
                          <div class="el-image">
                            <img :src="form.merchantDetailChart"
                                 width="100%"
                                 height="100%"
                                 class="el-image__inner"
                                 style="object-fit: cover" />
                          </div>
                          <div class="ele-image-upload-close"
                               @click="handleRemove('merchantDetailChart')"><i class="el-icon-close"></i></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div> -->
              </el-form-item>
            </el-col>

            <el-col :lg="12"
                    :md="10">
              <el-form-item label="营业时间:"
                            label-width="130px"
                            prop="dateRange">
                <el-time-picker is-range
                                v-model="dateRange"
                                range-separator="至"
                                start-placeholder="开始时间"
                                end-placeholder="结束时间"
                                value-format="HH:mm"
                                placeholder="选择时间范围">
                </el-time-picker>
                <!-- <el-date-picker v-model="dateRange"
                                type="daterange"
                                unlink-panels
                                :default-time="['00:00:00', '23:59:59']"
                                range-separator="-"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                                value-format="yyyy-MM-ddTHH:mm:ss"
                                class="ele-fluid" /> -->

                <!-- <el-input
                  v-model.trim="form.businessHours"
                  placeholder="请输入营业时间"
                  clearable
                ></el-input> -->
              </el-form-item>
              <el-form-item label="联系人:"
                            label-width="130px"
                            prop="contactPerson">
                <el-input v-model.trim="form.contactPerson"
                          placeholder="请输入联系人"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商家电话:"
                            label-width="130px"
                            prop="merchantPhone">
                <el-input v-model.trim="form.merchantPhone"
                          placeholder="请输入商家电话"
                          maxlength="11"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商家LOGO:"
                            prop="systemIcon">
                <span slot="label">
                  商家LOGO
                  <el-tooltip placement="top">
                    <div slot="content"> 大小尺寸为100px * 100px </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <!-- <ele-image-upload v-model="form.systemIcon" :limit="1" :drag="true" :multiple="false"  @upload="onUpload" /> -->
                <div class="ele-image-upload-list">
                  <div class="ele-image-upload-item ele-image-upload-button"
                       @click="modalPicTap('dan', 'merchantLogo', '商家LOGO')">
                    <div>
                      <div tabindex="0"
                           class="el-upload el-upload--text">
                        <div class="el-upload-dragger">
                          <i class="el-icon-plus ele-image-upload-icon"></i>
                        </div>

                        <div class="ele-image-upload-item"
                             style="margin: 0 0 0 0"
                             v-if="form.merchantLogo">
                          <div class="el-image">
                            <img :src="form.merchantLogo"
                                 width="100%"
                                 height="100%"
                                 class="el-image__inner"
                                 style="object-fit: cover" />
                          </div>
                          <div class="ele-image-upload-close"
                               @click="handleRemove('merchantLogo')"><i class="el-icon-close"></i></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!--上传图片组件-->
        <uploadPictures ref="upload"
                        :isChoice="isChoice"
                        :visible.sync="modalPic"
                        @getPic="getPic"
                        :gridBtn="gridBtn"
                        :gridPic="gridPic"
                        :title="modalTitle"></uploadPictures>

        <!-- 底部工具栏 -->
        <div class="ele-bottom-tool">
          <div v-if="validMsg"
               class="ele-text-danger">
            <i class="el-icon-circle-close"></i>
            <span>{{ validMsg }}</span>
          </div>
          <div class="ele-bottom-tool-actions">
            <el-button type="primary"
                       :loading="loading"
                       @click="submit">
              保存
            </el-button>
          </div>
        </div>
      </el-form>
    </div>
    <position ref="pos"
              @chooseMapPoint="getCallMap"
              @cancel="cancelMap"
              @sure="sure"></position>
  </div>
</template>
<script>
import axios from 'axios';
import position from './components/position.vue';
import { getToken } from '@/utils/token-util';
// import {
//   platformConfigAdd,
//   platformConfigDetail,
//   platformSettingsModify
// } from '@/api/platformSettings/index';
import {
  userOssSignature,
  mainOssSignature
} from '@/api/creatCenter/material';
import {
  addMerchantinfo,
  updateMerchantinfo,
  getMerchantinfo,
  merchantInformationSaveImg,
  merchantInformationDeleteImg,
  merchantInformationPageImg
} from '@/api/staffManage/merchantInformation/index.js';
import uploadPictures from './components/uploadImg';
// import { save, query } from '@/api/agent/pointAllocation';
const DEFAULT_FORM = {
  // oemId: this.$store.state.user.info.oemId,
  // systemIcon: [],
  // site_name:'',
  // browserIcon:[],
  // site_copyright:'',
  // site_beian:'',
  // site_jingbeian:'',
  // loginBackground: [],
  // loginLeftIcon:[],
  // kf_date:'',
  // serviceQrCode:[],
  // kf_mailbox:'',
  // kf_phone:'',
  // kf_address:'',
};
import EleImageUpload from 'ele-admin/es/ele-image-upload';
import request from '@/utils/request';

export default {
  name: 'FormAdvanced',
  components: { uploadPictures, position, EleImageUpload },
  data () {
    return {
      // 复选框
      checkList: ['D音H5任务发布'],
      // 能力名称——能力选择——复选框
      checkSelList: [],
      modalTitle: '',
      modalPic: false,
      isChoice: '单选',
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      // 表单提交状态
      loading: false,
      // 表单数据
      form: {
        // 商家名称
        merchantName: '',
        // 营业时间开始时间
        businessHoursStart: '',
        // 营业时间结束时间
        businessHoursEnd: '',
        // 经度
        longitude: '',
        // 结度
        latitude: '',
        // 商家地址
        merchantAddress: '',

        // 商家电话
        merchantPhone: '',
        // 联系人
        contactPerson: '',
        // 商家封面图
        merchantSurfaceDrawing: '',
        // 商家LOGO
        merchantLogo: '',
        // 商家详情图
        merchantDetailChart: '',

        id: this.$store.state.user.info.merchantId
      },
      dateRange: [],
      isUpdata: false,
      // 表单验证规则
      rules: {
        merchantName: [
          {
            required: true,
            message: '请输入商家名称',
            trigger: 'blur'
          }
        ],
        // merchantAddress: [
        //   {
        //     required: true,
        //     message: '请输入商家地址',
        //     trigger: 'blur'
        //   }
        // ],
        merchantPhone: [
          {
            required: true,
            message: '请输入商家电话',
            trigger: 'blur'
          }
        ],
        contactPerson: [
          {
            required: true,
            message: '请输入联系人',
            trigger: 'blur'
          }
        ],
        // dateRange: [
        //   {
        //     required: true,
        //     message: '请选择营业时间',
        //     trigger: 'blur'
        //   }
        // ],
        type: [
          {
            required: true,
            message: '请选择仓库类型',
            trigger: 'blur'
          }
        ],
        task: [
          {
            required: true,
            message: '请输入任务名',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入任务表述',
            trigger: 'blur'
          }
        ],
        executor: [
          {
            required: true,
            message: '请选择执行人',
            trigger: 'blur'
          }
        ],
        officer: [
          {
            required: true,
            message: '请选择责任人',
            trigger: 'blur'
          }
        ],
        reminder: [
          {
            required: true,
            message: '请选择提醒时间',
            trigger: 'blur'
          }
        ],
        taskType: [
          {
            required: true,
            message: '请选择任务类型',
            trigger: 'blur'
          }
        ]
      },
      // 表单验证信息
      validMsg: '',
      checkAll: [],
      checkSelAll: [],
      visibleMap: false,
      imgStr: [],
      fileList: []
    };
  },
  activated () {
    this.querys();
  },
  methods: {
    //腾讯地图

    // 调用
    selPosition () {
      this.$nextTick(() => {
        // console.log(this.$refs['pos']);
        this.$refs['pos'].show(); // 视频号二维码展示
      });
    },
    // 地图 初始值
    getCallMap (e) {
      // console.log(e);
    },
    sure (e) {
      console.log(e);
      this.form.merchantAddress = e.address;

      this.form.longitude = Number(e.lng)
      this.form.latitude = Number(e.lat)
    },
    // 地图 取消
    cancelMap () {
      this.visibleMap = false;
    },
    querys () {
      this.fileList = []
      // 查询回显
      getMerchantinfo({
        id: this.$store.state.user.info.merchantId
      })
        .then((msg) => {

          if (msg.code == 2000 && msg.data) {
            //   是修改


            this.$util.assignObject(this.form, {
              ...msg.data
            });
            this.form.id = msg.data.id;
            this.dateRange = [this.form.businessHoursStart, this.form.businessHoursEnd]
            const imgStr = msg.data.merchantDetailChart;
            if (imgStr) {
              if (imgStr.includes(',')) {
                console.log('字符串中包含逗号');
                // 包含的进行slice(',') 分割

                this.fileList = imgStr.split(',').map((item, index) => {
                  return {
                    uid: index,
                    url: item,
                    status: 'done'
                  };
                });
                this.form.merchantDetailChart = this.fileList;
              } else {
                console.log('字符串中不包含逗号');
                this.fileList = imgStr.split().map((item, index) => {
                  return {
                    uid: index,
                    url: item,
                    status: 'done'
                  };
                });
              }
              this.form.merchantDetailChart = this.fileList;
            } else {
              this.$message({
                message: '没有上传图片无法进行预览',
                type: 'warning'
              });
            }

            this.isUpdata = true;

          } else {
            // 添加
            this.isUpdata = false;
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    checkClick (e) {
      console.log('e=====', e);
      this.checkAll = e;
    },
    checkSelClick (e) {
      console.log('e=====', e);
      this.checkSelAll = e;
    },
    // 选择图片
    modalPicTap (tit, picTit, openTitle) {
      this.modalTitle = openTitle;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.modalPic = true;
      this.$nextTick(() => {
        this.$refs['upload'].show();
      });
    },
    // 选中图片
    getPic (pc) {
      console.log('pc========', pc);
      switch (this.picTit) {
        case 'merchantSurfaceDrawing':
          this.form.merchantSurfaceDrawing = pc.imgUrl;
          break;
        case 'merchantLogo':
          this.form.merchantLogo = pc.imgUrl;
          break;
        case 'merchantDetailChart':
          this.form.merchantDetailChart = pc.imgUrl;
          break;
      }
      this.modalPic = false;
    },
    //删除图片
    handleRemove (field) {
      this.form[field] = '';
    },
    /* 表单提交 */
    submit () {
      this.$refs['form'].validate((valid, obj) => {

        console.log(this.dateRange)
        if (valid) {
          // 手机号验证
          if (!this.form.merchantSurfaceDrawing) {
            this.$message.error('请选择商家封面图')
            return
          }
          if (!this.form.merchantLogo) {
            this.$message.error('请选择商家LOGO')
            return
          }
          if (!this.form.merchantDetailChart) {
            this.$message.error('请选择商家详情图')
            return
          }
          if (!this.form.merchantAddress) {
            this.$message.error('请输入商家地址')
            return
          }
          this.loading = true;

          const data = {
            ...this.form,
            id: this.$store.state.user.info.merchantId
          };
          if (!this.dateRange?.length) {
            this.$message.error('请填写营业时间')
            return
          }
          // 吧数组变成字符串提交
          const imgArr = data.merchantDetailChart.map((item) => {
            return item.url;
          });

          data.merchantDetailChart =
            imgArr.length === 1 ? imgArr[0].toString() : imgArr.join(',');


          data.businessHoursStart = this.dateRange[0];
          data.businessHoursEnd = this.dateRange[1];
          console.log(data);
          const saveOrUpdate = this.isUpdata
            ? updateMerchantinfo
            : addMerchantinfo;

          saveOrUpdate(data)
            .then((msg) => {
              this.loading = false;

              this.querys();
              //   if (!this.isUpdata) {

              //   }
              // }
              this.$message.success('提交成功！');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          this.validMsg = ` 共有校验 ${Object.keys(obj).length} 项不通过`;
          return false;
        }
      });
    },
    // ===========================

    async onUpload (item) {
      // console.log('this.fileListthis.fileListthis.fileList', this.fileList);
      this.data = await mainOssSignature();
      console.log(item);
      let file = item.file;

      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', this.data.dir + date + suffix);
      param.append('policy', this.data.policy);
      param.append('OSSAccessKeyId', this.data.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', this.data.signature);
      param.append('file', file, file.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);
      axios
        .post(this.data.host, param, config)
        .then((res) => {
          if (res.status == 200) {
            console.log(
              'this.data.host',
              this.data.host + '/' + date + suffix
            );
            let url = this.data.host + '/' + date + suffix;
            let type = file.type;
            console.log('file.type', file.type);

            this.fileList.push({
              url: url,
              status: 'done'
            });
            this.form.merchantDetailChart = this.fileList;

            console.log('url', this.form.merchantDetailChart + '===========');
          } else {
            this.$message.error('上传失败');
          }
        })
        .catch((err) => {
          console.log(err);
        });

    },
    removeHandler (item) {
      console.log(this.fileList);
      const index = this.fileList.findIndex((items) => {
        return items.url == item.url
      })
      console.log(index)
      this.fileList.splice(index, 1)
      this.form.merchantDetailChart = this.fileList
    }
  }
};
</script>
<style lang="less" scoped>
.ele-body {
  height: 80vh;
  background-color: #fff;
}
/deep/.ele-bottom-tool-actions {
  text-align: center;
}
</style>
